package com.vmock.biz.tcp;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.vmock.base.core.response.IMockResponse;
import com.vmock.base.utils.BizUtils;
import com.vmock.biz.entity.Log;
import com.vmock.biz.entity.Response;
import com.vmock.biz.entity.Url;
import com.vmock.biz.service.ILogService;
import com.vmock.biz.service.IResponseService;
import com.vmock.biz.service.IUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@Component
public class TcpServer {

    private static ConcurrentMap<Integer,TcpConn> serverMap = new ConcurrentHashMap<Integer,TcpConn>(10) ;

    @Autowired
    private IUrlService mockUrlService;

    @Autowired
    private IResponseService mockResponseService;

    @Autowired
    private ILogService logService;
    @PostConstruct
    public void init(){
        List<Url> urls = mockUrlService.selectMockUrlList(new Url());
        urls.stream().filter(item->(item.getType().equals(ProtocolTypeEnum.TCP.getCode()))).forEach((item)->{
            serverMap.put(item.getPort(),new TcpConn(item, mockResponseService,logService));
        });
        log.info("TCP server num = "+ serverMap.size());
    }

    public void removeServer(String id) {
        Url url = mockUrlService.selectOneUrlById(id);
        if (null != url && ProtocolTypeEnum.TCP.getCode().equals(url.getType())){
            TcpConn tcpConn = serverMap.get(url.getPort());
            if (tcpConn == null){
                log.warn("此服务器未启动：port = {}", url.getPort());
                return;
            }
            tcpConn.setStatus(TcpServerStatusEnum.STOP);
            serverMap.remove(url.getPort());
            try {
                ServerSocket ss = tcpConn.getServerSocket();
                if (ss != null) {
                    tcpConn.getServerSocket().close();
                }
                log.info(url.getPort()+" 服务移出！");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void addServer(Url item) {
        if (null != item){
            Response response = mockResponseService.selectMainResponse(item.getUrlId());
            serverMap.put(item.getPort(),new TcpConn(item, mockResponseService, logService));
        }
    }
}
